import * as actionTypes from "./constants"

const initialstate = {
    goods: [],  //购物车中的全部商品
    isAllSelect: false,  //是否全选
    isDeleteState: false  //是否是删除状态
}

//因为拿到的数据是对象，所以要转换成json格式，先转换成字符串形式，任何转json格式
const reducer = (state = initialstate, action) => {
    switch (action.type) {
        case actionTypes.CHANGE_GOODS:
            return { ...state, goods: JSON.parse(JSON.stringify([...state.goods, action.data])), isAllSelect: false }
        case actionTypes.CHANGE_GOODS_COUNT:
            let newGoods = state.goods;
            newGoods[action.index].count++;
            return { ...state, goods: JSON.parse(JSON.stringify(newGoods)) }
        case actionTypes.CHANGE_SELECT:
            let setSelect = state.goods;
            setSelect[action.index].isSelect = !setSelect[action.index].isSelect;
            if (state.goods.findIndex((item) => item.isSelect == false) == -1) {
                state.isAllSelect = true
            } else {
                state.isAllSelect = false
            }
            return { ...state, goods: JSON.parse(JSON.stringify(setSelect)), isAllSelect: state.isAllSelect }
        case actionTypes.ADD_COUNT:
            let addCount = state.goods;
            addCount[action.index].count++;
            return { ...state, goods: JSON.parse(JSON.stringify(addCount)) }
        case actionTypes.SUB_COUNT:
            let subCount = state.goods;
            subCount[action.index].count--;
            return { ...state, goods: JSON.parse(JSON.stringify(subCount)) }
        case actionTypes.DELETE_STATE:
            let newDelete = state.goods;
            return { ...state, goods: JSON.parse(JSON.stringify(newDelete)), isDeleteState: !state.isDeleteState }
        case actionTypes.ALL_SELECT:
            let newSelect = state.goods;
            if (state.isAllSelect && state.goods.findIndex((item) => item.isSelect == false) == -1) {
                state.goods.map((item) => {
                    item.isSelect = false;
                })
            } else {
                state.goods.map((item) => {
                    if (item.isSelect == false) {
                        item.isSelect = !item.isSelect;
                    }
                })

            }
            return { ...state, goods: JSON.parse(JSON.stringify(newSelect)), isAllSelect: !state.isAllSelect }
        case actionTypes.DELECT_SELECT:
            let arr = []
            state.goods.map((item, index) => {
                if (item.isSelect == false) {
                    arr.push(state.goods[index])
                }
            })
            return { ...state, goods: JSON.parse(JSON.stringify(arr)) }
        default:
            return state

    }
}

export default reducer;